package controllers;

import gateway.CarpoolDB;
import gateway.DatabaseGateway;
import gateway.exception.CarpoolDBException;
import model.Carpool;
import play.libs.Crypto;
import play.libs.Json;
import play.mvc.*;
import session.CookieManager;
import session.SessionManager;
import views.html.*;

import java.sql.SQLException;
import java.util.List;


public class Application extends Controller {

    public static Result index() {
        if (session().containsKey("username")){
            return group_index();
        }

        //if cookie rememberme isset .. set session
        String rememberme_email = CookieManager.getRememberMe();
        if (rememberme_email != null){
            // TODO check if the email still exists, don't log in a non existing user.
            session().put("username", Crypto.decryptAES(rememberme_email));
            return redirect(routes.Application.index());

        }

        return redirect(routes.UserActions.loginForm());

    }



    public static Result group_index(){

        String groups_json = CookieManager.getGroup_ids();
        if (groups_json != null){
            return redirect(routes.CarpoolDayActions.dayOverview());
            //return ok(index.render("AtagCarpool", "<p>You're in the groups: "+ groups_json +", obtained from cookie</p>"));
        }


        CarpoolDB db = new CarpoolDB();
        List<Carpool> group_ids;
        try {
            group_ids = db.getJoinedCarpoolGroups(session().get("username"));
            CookieManager.setGroup_ids(group_ids);

            if (group_ids.size() !=0 ){
                return redirect(routes.CarpoolDayActions.dayOverview());
                //return ok(index.render("AtagCarpool", "<p>You're in the groups: "+ Json.toJson(group_ids) +", obtained from database</p>"));
            }

            System.out.println("User "+session().get("username")+" is not in any groups");
            return redirect(routes.GroupActions.joinGroupForm());


        } catch (CarpoolDBException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return ok(debug_index.render("AtagCarpool"));
    }





    public static Result test(){
        SessionManager sm = new SessionManager();
        return ok(debug.render("current username: " + sm.getUsername()));
    }

}
